﻿using ApiCommon;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Http.Filters;
using WeiXinMongoApis.Controllers;

namespace WeiXinMongoApis
{
    public class WeiXinMongoExceptionFilterAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            ApiException apiException = actionExecutedContext.Exception as ApiException;
            if (apiException != null)
            {
                ObjectContent oc = new ObjectContent(
                     typeof(ApiError)
                    , new ApiError() { Code = apiException.Code, Message = actionExecutedContext.Exception.Message }
                    , new System.Net.Http.Formatting.JsonMediaTypeFormatter()
                );
                actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(System.Net.HttpStatusCode.OK);
                actionExecutedContext.Response.Content = oc;
            }
            else
            {
                base.OnException(actionExecutedContext);
            }
        }
    }
}